#include <iostream>
#include <algorithm>
#include "CompareResult.h"
using namespace TextDiffAlgo;

void CompareResult::initialize()
{
	mResVector.clear();
}

void CompareResult::destroy()
{

}

TextDiff* CompareResult::getVector()
{
	TextDiff* it = &mResVector[0];
	return it;
}

int CompareResult::getLength()
{
	return mResVector.size();
}

double CompareResult::compare(std::string before, std::string after)
{
	// return the similarity degree.
	std::list<TextDiff> diffList = TextDiffAlgo::TextComparer::GetInstance()->compare(before, after);
	std::vector<TextDiffAlgo::TextDiff> diffArrays;
	diffArrays.clear();
	for (std::list<TextDiffAlgo::TextDiff>::iterator it = diffList.begin(); it != diffList.end(); it++) {
		diffArrays.push_back(*it);
	}
	std::sort(diffArrays.begin(), diffArrays.end());

	int deleteIndex = 0, addIndex = 0;
	int same = 0;
	std::string content, keeped;

	for (int i = 0; i < diffArrays.size(); i++) {
		std::cout << diffArrays[i].toString() << std::endl;
		mResVector.push_back(diffArrays[i]);
	}

	for (int i = 0; i < diffArrays.size(); i++) {
		TextDiffAlgo::TextDiff diff = diffArrays[i];
		if (diff.getDiffType() == TextDiffAlgo::TextDiff::DiffType::TYPE_DELETED) {
			if (deleteIndex < diff.getDiffStartIndex() && diff.getDiffStartIndex() < before.length()) {
 				keeped = before.substr(deleteIndex, diff.getDiffStartIndex() - deleteIndex);
 				std::cout << "remain: " << keeped << std::endl;
				mResVector.push_back(TextDiff(TextDiff::DiffType::TYPE_SAME_BEFORE, deleteIndex, diff.getDiffStartIndex() - deleteIndex));
				same += diff.getDiffStartIndex() - deleteIndex;
				addIndex += diff.getDiffStartIndex() - deleteIndex;
				deleteIndex = diff.getDiffStartIndex();
			}
			content = before.substr(diff.getDiffStartIndex(), diff.getDiffLength());
			std::cout << "del: " << content << "\t" << diff.toString() << std::endl;
			deleteIndex += diff.getDiffLength();
		} else if (diff.getDiffType() == TextDiffAlgo::TextDiff::DiffType::TYPE_INSERTED) {
			if (addIndex < diff.getDiffStartIndex() && diff.getDiffStartIndex() < after.length()) {
				keeped = after.substr(addIndex, diff.getDiffStartIndex() - addIndex);
				std::cout << "remain: " << keeped << std::endl;
				mResVector.push_back(TextDiff(TextDiff::DiffType::TYPE_SAME_AFTER, addIndex, diff.getDiffStartIndex() - addIndex));
				same += diff.getDiffStartIndex() - addIndex;
				deleteIndex = diff.getDiffStartIndex() - addIndex;
				addIndex = diff.getDiffStartIndex();
			}
			content = after.substr(diff.getDiffStartIndex(), diff.getDiffLength());
			std::cout << "add: " << content << "\t" << diff.toString() << std::endl;
			addIndex += diff.getDiffLength();
		}
	}

	sort(mResVector.begin(), mResVector.end());

	return (double) same / (double) (before.length() + after.length());
}
